package com.nibian.nibian.fragment;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nibian.nibian.R;
import com.nibian.nibian.activity.MainActivity;
import com.nibian.nibian.bean.TextBean;
import com.nibian.nibian.ui.ProgressDialogs;
import com.nibian.nibian.utils.LanguagesUtils;
import com.nibian.nibian.utils.SharedPreferenceTools;
import com.nibian.nibian.utils.UiUtils;
import com.nibianplus.base.BaseFragment;
import com.nibianplus.base.BaseObject;

import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;


/**
 * @创建者 luck
 * @创建时间 ${DATA} 15:00
 * @描述 ${设备信息}
 * @更新者 $Author$
 * @更新时间 $Date$
 * @更新描述 ${TODO}
 */
public class SheBeiFragment extends BaseFragment {
    @BindView(R.id.ll_search_bt)
    LinearLayout ll_search_bt;              //搜索蓝牙
    @BindView(R.id.conn_state)
    TextView conn_state;                    //连接状态
    @BindView(R.id.banben_tv)
    TextView banben_tv;                     //设备版本
    @BindView(R.id.rl_laungageswitch)
    RelativeLayout rl_laungageswitch;       //语言切换
    @BindView(R.id.iv_laungageswitch)
    ImageView iv_laungageswitch;            //图片更换
    @BindView(R.id.tv_sncode)
    TextView tv_sncode;                     //Sn码
    @BindView(R.id.tv_sbxh)
    TextView tv_sbxh;                       //设备型号
    @BindView(R.id.tv_cleardata)
    TextView tv_cleardata;                  //恢复出厂设置
    @BindView(R.id.tv_clear_history)
    TextView tvClearHistory;
    private BluetoothAdapter mBluetoothAdapter;
    private boolean isOpenBlueToolth = true;
    private Dialog loading;   //正在加载
    private String mLanguages_key;
    public static SheBeiFragment sSheBeiFragment;
    private View mInflate;

    public static SheBeiFragment getInstance() {
        return sSheBeiFragment;
    }

    /**
     * 实现广播监听
     */
    public static BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BluetoothDevice.ACTION_FOUND)) {                                      // 获得已经搜索到的蓝牙设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {                         // 搜索到的不是已经绑定的蓝牙设备
                }
            } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {                 // 搜索完成
                UiUtils.toast("搜索完成");
            }
        }
    };

    /**
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        sSheBeiFragment = this;
        mLanguages_key = SharedPreferenceTools.getString(UiUtils.getContext(), "LANGUAGES_KEY", "zh");
        if (mLanguages_key.equals("zh")) {
            loading = ProgressDialogs.getLoading(getActivity(), "正在加载...");
        } else {
            loading = ProgressDialogs.getLoading(getActivity(), "loading...");
        }
        loading.show();
        if (mInflate == null) {
            MainActivity.getInstance().sendSheBeiData();
            MainActivity.getInstance().showJianKongFra();
            mInflate = View.inflate(UiUtils.getContext(), R.layout.root_data, null);
            ButterKnife.bind(this, mInflate);
        }
        setLaungageSwitch();

        if (MainActivity.getInstance().isConnect == false) {                                         //设备连接是否成功
            if (mLanguages_key.equals("zh")) {
                conn_state.setText("设备断开连接");
            } else {
                conn_state.setText("Device disconnect");
            }
        } else {
            if (mLanguages_key.equals("zh")) {
                conn_state.setText("设备连接成功");
            } else {
                conn_state.setText("Device connection success");
            }
        }
        boolean registered = EventBus.getDefault().isRegistered(this);
        if (registered == false) {
            EventBus.getDefault().register(this);                                                   //注册eventBus - 响应mainactivity的弹出搜索的窗口
        }

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();                         // 获取所有已经绑定的蓝牙设备
        if (devices.size() > 0) {
//            for (BluetoothDevice bluetoothDevice : devices) {
//                text_view.append(bluetoothDevice.getName() + ":"                                  //Textvew显示搜索到的数据
//                        + bluetoothDevice.getAddress() + "\n\n");
//            }
        }
        IntentFilter mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);        // 注册用以接收到已搜索到的蓝牙设备的receiver
//        LocalBroadcastManager.getInstance(UiUtils.getContext()).registerReceiver(mReceiver, mFilter);
        getActivity().registerReceiver(mReceiver, mFilter);
        mFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);                                    // 注册搜索完时的receiver
        getActivity().registerReceiver(mReceiver, mFilter);
        return mInflate;
    }

    /**
     * 语言切换图片设置
     */
    private void setLaungageSwitch() {
        if (mLanguages_key.equals("zh")) {                             //显示中文
            iv_laungageswitch.setBackgroundResource(R.mipmap.laungagezn);
        } else {                                                       //显示英文
            iv_laungageswitch.setBackgroundResource(R.mipmap.laungageen);
        }
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @OnClick({R.id.ll_search_bt, R.id.rl_laungageswitch, R.id.tv_cleardata, R.id.tv_clear_history})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_search_bt:
                EventBus.getDefault().post("startSearch");                   //搜索 - 事件总线启动搜索界面
                break;
            case R.id.rl_laungageswitch:                                     //语言切换
                if (mLanguages_key.equals("zh")) {
                    iv_laungageswitch.setBackgroundResource(R.mipmap.laungageen);
                    LanguagesUtils.switchLanguage(getActivity(), LanguagesUtils.EN);
                } else {
                    iv_laungageswitch.setBackgroundResource(R.mipmap.laungagezn);
                    LanguagesUtils.switchLanguage(getActivity(), LanguagesUtils.ZH);
                }
                break;
            case R.id.tv_cleardata:                                           //恢复出厂设置
                clearData();
                break;
            case R.id.tv_clear_history:
                clearHistory();
                break;
        }
    }


    /**
     * 取消广播
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (loading != null) {
            loading.cancel();
        }
        EventBus.getDefault().unregister(this);
        getActivity().unregisterReceiver(mReceiver);
    }

    /**
     * 回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:                                                                                 //判断蓝牙是否打开
                if (resultCode == Activity.RESULT_OK) {
                    if (isOpenBlueToolth == false) {
                        UiUtils.toast("请打开位置信息");
                        if (Build.VERSION.SDK_INT >= 23 && !isLocationOpen(UiUtils.getContext())) { //蓝牙打开 - 位置信息没有打开 - 跳转位置打开
                            Intent enableLocate = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(enableLocate, 2);
                        }
                        return;
                    }
                    if (mBluetoothAdapter.isDiscovering()) {                                         // 蓝牙打开 - 如果正在搜索，就先取消搜索
                        mBluetoothAdapter.cancelDiscovery();
                    }
                    mBluetoothAdapter.startDiscovery();                                              // 开始搜索蓝牙设备,搜索到的蓝牙设备通过广播返回
                } else {
                    UiUtils.toast("蓝牙开启失败");
                    return;
                }
                break;
            case 2:
                if (isLocationOpen(UiUtils.getContext())) {                                         //打开位置信息
                    isOpenBlueToolth = true;
                    //Android6.0需要动态申请权限
                    if (ContextCompat.checkSelfPermission(UiUtils.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION)
                            != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(getActivity(),                            //请求权限
                                new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                                        Manifest.permission.ACCESS_FINE_LOCATION}, 2);
                        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                                Manifest.permission.ACCESS_COARSE_LOCATION)) {
                            UiUtils.toast("需要蓝牙权限");                                           //判断是否需要解释
                        }
                    }
                } else {                                                                            //若未开启位置信息，提示
                    UiUtils.toast("请打开位置信息");
                    isOpenBlueToolth = false;
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 判断位置信息是否开启
     *
     * @param context
     * @return
     */
    public static boolean isLocationOpen(final Context context) {
        LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean isGpsProvider = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);            //gps定位
        boolean isNetWorkProvider = manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);     //网络定位
        return isGpsProvider || isNetWorkProvider;
    }

    /**
     * 事件总线
     *
     * @param action
     */
    @Subscribe
    public void onEvent(String action) {
        switch (action) {
            case "connectSuccess":              //连接成功的时候进行改变状态
                if (mLanguages_key.equals("zh")) {
                    conn_state.setText("设备连接成功");
                } else {
                    conn_state.setText("Device connection success");
                }
                break;
        }
    }

    /**
     * 断开连接
     */
    public void connectCut() {
        if (mLanguages_key.equals("zh")) {
            conn_state.setText("设备断开连接");
        } else {
            conn_state.setText("Device disconnect");
        }
    }

    /**
     * 回复出厂设置
     */
    private void clearData() {
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setTitle("温馨提示：")
                .setMessage("是否确认恢复出厂设置？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        MainActivity.getInstance().sendClearData();
                    }

                }).setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                return;
                            }
                        }).create();
        alertDialog.show();
    }

    private void clearHistory() {
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setTitle("温馨提示：")
                .setMessage("是否确认清空历史数据？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        MainActivity.getInstance().sendClearHistory();
                    }

                }).setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                return;
                            }
                        }).create();
        alertDialog.show();
    }

    @Override
    public void refreshUI(BaseObject object, int what) {
    }

    @Override
    protected BaseObject createDataObject() {
        return TextBean.getInstance(getTagName());
    }


    public void setUiData(int dataCount, String data) {
        try {
            if (dataCount == 0) {
                //ffff021501031020202020 4d4c 3234 3330 202020, 2020202527aaaa
                String substring2 = data.substring(22, 34);                                            //设备型号直接进行显示
                Log.d("tag", substring2);
                String s = UiUtils.convertHexToString(substring2);
                tv_sbxh.setText(s);
            } else if (dataCount == 1) {
                //ffff 020d 0103 08   0001 0300 0000 0500 8674 aaaa
                String substring3 = data.substring(16, 18);                                               //读控制器软件版本和硬件版本
                String substring4 = data.substring(18, 20);
                String substring5 = data.substring(20, 22);
                banben_tv.setText("V" + substring3 + "." + substring4 + "." + substring5);
            } else if (dataCount == 2) {
                //SN码 - ffff 0209 0103 04 1123 0020 0f1d aaaa
                String subs = data.substring(18, 22);
                int i = UiUtils.toTen(subs);
                tv_sncode.setText(i + "");
            }
        } catch (Exception e) {
        }

    }

    /**
     * 设置UI数据
     *
     * @param list
     */
    public void setUiData(List<String> list) {
        //[ffff000c5452414e53504f52543d320daaaa, ffff0215010310202020204d4c32343330202020, 2020202527aaaa, ffff020d01030800010300000005008674aaaa,ffff 0209 0103 04 1123 0020 0f1d aaaa]

        if (list != null && list.size() >= 5) {
            Log.d("mListDataa", list + "");

            try {
                //ffff021501031020202020 4d4c 3234 3330 202020, 2020202527aaaa
                String s1 = list.get(1);
                String substring2 = s1.substring(22, 34);                                            //设备型号直接进行显示
                Log.d("tag", substring2);
                String s = UiUtils.convertHexToString(substring2);
                tv_sbxh.setText(s);

                //ffff 020d 0103 08   0001 0300 0000 0500 8674 aaaa
                String s2 = list.get(3);
                String substring3 = s2.substring(16, 18);                                               //读控制器软件版本和硬件版本
                String substring4 = s2.substring(18, 20);
                String substring5 = s2.substring(20, 22);
                banben_tv.setText("V" + substring3 + "." + substring4 + "." + substring5);

                //SN码 - ffff 0209 0103 04 1123 0020 0f1d aaaa
                String s3 = list.get(4);                                                                //产品序列号
                String subs = s3.substring(18, 22);
                int i = UiUtils.toTen(subs);
                tv_sncode.setText(i + "");
            } catch (Exception e) {
            }
            list.clear();
        }

    }
}
